import dayjs from 'dayjs'
import behavior from '../../../utils/behaviors'

Page({
  behaviors: [behavior],
  data: {
    dateLayerVisible: false,
    houseLayerVisible: false,
    name: '',
    mobile: '',
    gender: 1,
    houseList: [], // 报修房屋列表
    visitDate: '', // 选中的日期 字符串形式
    currentDate: Date.now(), // 选中的日期，时间戳形式
    minDate: Date.now() + 86400 * 1000,
    maxDate: Date.now() + 86400 * 1000 * 3
  },
  rules: {
    houseId: [
      { required: true, message: '请选择到访的房屋!' }
    ],
    name: [
      { required: true, message: '访客姓名不能为空!' },
      { pattern: /[\u4e00-\u9fa5]{2,5}/, message: '访客姓名只能为中文!' },
    ],
    mobile: [
      { required: true, message: '访客手机号不能为空!' },
      { pattern: /^1[3-9]\d{9}$/, message: '请填写正确的手机号码!' },
    ],
    visitDate: [
      { required: true, message: '请选择到访的日期!' }
    ],
  },
  onLoad() {
    this.getHouseList()
  },
  // 获取房屋列表
  async getHouseList() {
    const houseList = await wx.http({
      url: '/room',
    })
    this.setData({
      houseList
    })
  },
  // 选中房屋名字
  selectHouse(ev) {
    this.setData({
      houseInfo: ev.detail.point + ev.detail.building + ev.detail.room,
      houseId: ev.detail.id
    })
  },
  // 确认预约日期
  confirmDate(ev) {
    this.setData({
      visitDate: dayjs(ev.detail).format('YYYY-MM-DD'), //给van-cell显示用
      currentDate: ev.detail, // 给vant-detetime-picker组件用，发现传格式化后的字符串报错，所以传时间戳
      dateLayerVisible: false,
    })
  },

  openHouseLayer() {
    this.setData({ houseLayerVisible: true })
  },
  closeHouseLayer() {
    this.setData({ houseLayerVisible: false })
  },
  openDateLayer() {
    this.setData({ dateLayerVisible: true })
  },
  closeDateLayer() {
    this.setData({ dateLayerVisible: false })
  },
  // 确认提交  逻辑
  async goPassport() {
    // 1. 校验
    const validateRules = this.validate()
    if (!validateRules) return
    // 2. 调接口
    const { houseId, name, gender, mobile, visitDate } = this.data
    const { id } = await wx.http({
      url: '/visitor',
      method: 'POST',
      data: { houseId, name, gender, mobile, visitDate }
    })
    // 3. 成功提示
    wx.showToast({
      title: '填写访客信息成功',
    })
    // 4. 跳转页面
    wx.reLaunch({
      url: '/visitor_pkg/pages/passport/index?id=' + id,
    })
  },
})
